//
//  NGUtility.m
//  Mobil Izleme
//
//  Created by Mehmet Sinan Şahin on 1/2/12.
//  Copyright (c) 2012 netgis. All rights reserved.
//

#import "NGUtility.h"
#import "NGLocation.h"
#import "Math.h"
#import "Status.h"
#import "NSString+Extensions.h"
#import "TTGlobalCoreLocale.h"
#import "Command.h"
#import "SetLocationsResponse.h"
#import "SoapFault.h"

@implementation NGUtility

NSString * const TEST_DEVICE_ID = @"sinan-ios-1234";
NSString * const APP_SETTING_SEND_TO_SERVER = @"sendToServer";
NSString * const APP_SETTING_USE_GPS = @"useGPS";
NSString * const APP_SETTING_SIGNIFICANT_LOCATION_UPDATE = @"significantLocationUpdate";
NSString * const APP_SETTING_LOCATION_SIZE = @"locationSizePref";
NSString * const APP_SETTING_SEND_FREQUENCY = @"sendFrequencyPref";
NSString * const APP_SETTING_SERVICE_URL = @"serviceURL";
NSString * const APP_SETTING_DELTA_DISTANCE = @"minDistancePref";
NSString * const APP_SETTING_TIME_INTERVAL = @"minTimePref";
NSString * const APP_SETTING_SESSION_ID = @"sessionID";
NSString * const APP_SETTING_USERNAME = @"userName";
NSString * const APP_SETTING_PASSWORD = @"password";

NSString * const APP_SETTING_DB_MODEL_VERSION = @"db_model_version";
NSString * const APP_SETTING_SERVICE_AGGREMENT = @"serviceAggrement";

NSString * const TEST_SERVER_URL = @"http://213.139.195.74/MTS/GenericClass/DataRetrievingService.asmx";
NSString * const DATE_PATTERN = @"dd-MM-yyyy HH:mm:ss";
NSString * const DATE_PATTERN_WITH_DOT = @"dd.MM.yyyy HH:mm:ss";

NSString * const TIME_PATTERN = @"HH:mm:ss";
int const MESSAGES_SIZE = 9; //how many message will be recorded in database
float const eV = 5;
int const LAST_N_LOCATIONS_SIZE = 10;
int const MAX_VALUES_TO_BE_DISPLAYED = 100;

+(NSString *)getDeviceId {
    #if TARGET_IPHONE_SIMULATOR
        return @"11d08075cd3858260729bac5bc2138fa4aa3d38b"; //sina'nın cebi
    #endif
    UIDevice *device = [UIDevice currentDevice];
    NSString *uniqueIdentifier = [device uniqueIdentifier];
    //NSLog(@"%@", uniqueIdentifier);
    return uniqueIdentifier;
}

/*
 * If app is in backgroud, badge number is updated by updated location number.
 */
+(void)setBadgeNumberForBackground {
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
        UILocalNotification *localNotification = [[[UILocalNotification alloc] init] autorelease];
        if (localNotification) {
            // Current date
            NSDate *date = [NSDate date]; 
            
            // Add one minute to the current time
            NSDate *dateToFire = [date dateByAddingTimeInterval:10];
            
            // Set the fire date/time
            [localNotification setFireDate:dateToFire];
            [localNotification setTimeZone:[NSTimeZone defaultTimeZone]];
            
            // Create a payload to go along with the notification
            NSArray *array = [NSArray arrayWithObjects:@"Value 1", @"Value 2", nil];
            NSDictionary *data = [NSDictionary dictionaryWithObject:array forKey:@"payload"];
            [localNotification setUserInfo:data];
            
            [localNotification setApplicationIconBadgeNumber:[[UIApplication sharedApplication] applicationIconBadgeNumber] + 1];
            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];   
            NSLog(@"background-localnotif");
        }
    }    
}

/**
 * km 
 * @param first
 * @param second
 * @return
 */
+ (double) distanceWithLocation:(NGLocation *)from to:(NGLocation *)to {
    if (from == nil || to == nil)
        return 0.0;
    return [self distance:from.lat lon1:from.lon lat2:to.lat lon2:to.lon unit:'K'];
}

+ (float) speed:(NGLocation *)from to:(NGLocation *)to {
    float speed = 0;
    if (from != nil && to != nil) {
        double timeIntervalAsSecond = [to.tarihSaat timeIntervalSinceDate:from.tarihSaat];
        double timeAsMinute = (double)(timeIntervalAsSecond / 60);
        speed = (float)((float)(60 * [self distanceWithLocation:from to:to]) / timeAsMinute);
    }
    return speed;
}

+ (double) distance:(double)lat1 lon1:(double)lon1 lat2:(double)lat2 lon2:(double)lon2 unit:(char)unit {
    double theta = lon1 - lon2;
    double dist = [Math sin:[Math deg2rad:lat1]] * [Math sin:[Math deg2rad:lat2]] + [Math cos:[Math deg2rad:lat1]] * [Math cos:[Math deg2rad:lat2]] * [Math cos:[Math deg2rad:theta]];
    dist = [Math acos:dist];
    dist = [Math rad2deg:dist];
    dist = dist * 60 * 1.1515;
    if (unit == 'K') {
        dist = dist * 1.609344;
    }
    else if (unit == 'N') {
        dist = dist * 0.8684;
    }
    return (dist);
}

+ (BOOL) isNotEmpty:(NSArray *) arr {
    return arr != nil && [arr count] > 0;
}

+ (NSArray *) sort:(NSArray *)arr  comparator:(id)comparator {
    NSArray *sortedArray;
    sortedArray = [arr sortedArrayUsingComparator:comparator];
    return sortedArray;
}

/*
 * returns image for location status 
 */
+ (UIImage *) imageForNGLocationStatus: (NGLocation *)location {
    int status = location.status;
    UIImage *image = nil;
    if (status == DURDU) {
        image = [UIImage imageNamed: @"ic_durdu.png"];
    } else if (status == HAREKET_EDIYOR) {
        image = [UIImage imageNamed: @"ic_hareketediyor.png"];        
    } else if (status == UYGULAMA_ACILDI) {
        image = [UIImage imageNamed: @"ic_uygulamaacildi.png"];        
    } else if (status == UYGULAMA_KAPANDI) {
        image = [UIImage imageNamed: @"ic_uygulamakapandi.png"];        
    } else {
        image = [UIImage imageNamed: @"ic_durdu.png"];
    }
    return image;
}

+ (UIImage *) imageForMessageType: (MESSAGE_TYPE) type {
    if (type == MESSAGE) {
        return [UIImage imageNamed: @"message_type_text.png"];
    }
    else if (type == COMMAND) {
        return [UIImage imageNamed: @"message_type_command.png"];        
    }      
    return [UIImage imageNamed: @"create_message.png"];            
}

+ (NSString *) friendlySpeed: (NGLocation *)location {
    if (location.speed == nil) {
        return @"";
    }
    double speed = [location.speed doubleValue];
    if (speed > eV) {
        int rounded = round(speed);
        return [NSString stringWithFormat:@"%d km/s", rounded];
    } else {
        return @"";
    }
}

+ (NSString *) friendlyDate: (NSDate *)date {
    return @"";
}

+ (NSString *) friendlyStatus: (NGLocation *)location {
    int status = location.status;
    if (status == UYGULAMA_ACILDI) {
        return TTLocalizedString(@"loc_status_uygulamaacildi", @"");
    } else if (status == UYGULAMA_KAPANDI) {
        return TTLocalizedString(@"loc_status_uygulamakapandi", @"");
    } else if (status == DURDU) {
        return TTLocalizedString(@"loc_status_durdu", @"");
    } else if (status == HAREKET_EDIYOR) {
        return TTLocalizedString(@"loc_status_hareketediyor", @"");
    } else if (status == BEKLENMEYEN_KAPANIS) {
        return TTLocalizedString(@"loc_status_beklenmeyenkapanis", @"");
    }
    return [NSString stringWithFormat:@"Status tanımsız: %d", status];
}

+ (NSString *) friendlyCommand: (Command *)command {
    if (command._command == LOCATION_SIZE) {
        return TTLocalizedString(@"txtLOCATION_SIZE", @"");
    } else if (command._command == MIN_DISTANCE) {
        return TTLocalizedString(@"txtMIN_DISTANCE", @"");        
    } else if (command._command == MIN_TIME) {
        return TTLocalizedString(@"txtMIN_TIME", @"");        
    } else if (command._command == SEND_FREQUENCY) {
        return TTLocalizedString(@"txtSEND_FREQUENCY", @"");        
    }
    return [NSString stringWithFormat:@"Geçersiz Komut: %d", command._command];
}

+ (void) alert: (NSString *)message title:(NSString *)title {
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle: title
                          message: message 
                          delegate:nil
                          cancelButtonTitle:TTLocalizedString(@"OK", @"")
                          otherButtonTitles:nil];
    [alert show];
    [alert release];    
}

+ (void) alertError: (NSString *)message {
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle: TTLocalizedString(@"Error", @"")
                          message: message 
                          delegate:nil
                          cancelButtonTitle:TTLocalizedString(@"OK", @"")
                          otherButtonTitles:nil];
    [alert show];
    [alert release];    
}


+ (void) alertForCannotAccessToURL: (NSString *)url {
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle: TTLocalizedString(@"Connection Error", @"")
                          message: [NSString stringWithFormat: TTLocalizedString(@"Cannot Access To Server: %@", @""), url]
                          delegate:nil
                          cancelButtonTitle:TTLocalizedString(@"OK", @"")
                          otherButtonTitles:nil];
    [alert show];
    [alert release];    
}

/**
 * if value is null or kind of error, return TRUE
 */
+ (BOOL) handleRequestForError:(id)value showAlert:(BOOL)showAlert {
    BOOL hasError = FALSE;
    NSString *message = nil;
    if (value == nil) {
        //NSLog(@"%@login handler nil.....", @"LoginViewController");
        message = TTLocalizedString(@"Value is null", @"");
        hasError = TRUE;
    }
	if([value isKindOfClass:[NSError class]]) {
        
		//NSLog(@"%@login handler NSERROR.....%@", @"LoginViewController", value);
        message = [((NSError *)value) localizedDescription];
        hasError = TRUE;
	}
    
	if([value isKindOfClass:[SoapFault class]]) {
        message = [((SoapFault *)value) description];
		//NSLog(@"%@login handler SOAP FAULT.....%@", @"LoginViewController", value);
        hasError = TRUE;
	}
    if (showAlert && hasError) {
        [NGUtility alertError: message];
    }
    
    return hasError;
}

@end
